package com.abel.bigwater.data.sanchuan

import com.abel.bigwater.data.BcdString
import com.alibaba.fastjson.JSON
import io.netty.buffer.Unpooled
import org.junit.Test
import org.slf4j.LoggerFactory
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.AsynchronousSocketChannel
import java.util.concurrent.TimeUnit

class SanchuanAioTest {
    @Test
    fun testGrpsOnline1() {
        val HOST_IWG = "intel-water.cn"
        val PORT_IWG = 9237
        val fmt = """
68 00 a1 68 10 05 18 07 00 11 11 18 06 36 88 00 00 00 7f 15 03 04 60 04 03 67 20 17 84 02 00 af
11 6c 09 01 20 20 04 19 02 00 9b 54 1a 00 9b 54 1a 00 a5 31 10 00 a5 31 10 00 a5 31 10 00 a5 31
10 00 a5 31 10 00 a5 31 10 00 a5 31 10 00 a5 31 10 00 a7 ee be 00 a8 4a 26 00 a8 a2 aa 00 a8 f7
1e 00 a9 54 fc 00 a9 b4 e2 00 aa 1c 48 00 aa 73 96 00 aa c9 f4 00 ab 1c 24 00 ab 76 2e 00 ab cc
b4 00 ac 1d a4 00 ac 76 5a 00 ac d0 50 00 ad 29 10 00 ad 7e 10 00 ad d2 8e 00 ae 29 b4 00 ae 84
90 00 ae e2 1e ee 16 
"""

        val asc = AsynchronousSocketChannel.open()
        try {
            val f1 = asc.connect(InetSocketAddress(HOST_IWG, PORT_IWG))
            f1[3, TimeUnit.SECONDS]

            val bs = BcdString.toByteArray(fmt)
            SanchuanPacket.parseBuffer(Unpooled.wrappedBuffer(bs)).also {
                lgr.info("parsed buffer: {}", JSON.toJSONString(it, true))
            }
            val buf = ByteBuffer.wrap(bs)
            val f2 = asc.write(buf)
            f2[3, TimeUnit.SECONDS]

            buf.clear()
            val f3 = asc.read(buf)
            f3[3, TimeUnit.SECONDS]
            buf.flip()
            ByteArray(buf.remaining()).also {
                buf.get(it)
                lgr.info("got response: {}", BcdString.hexString(it, withBlank = true))
            }
        } finally {
            asc.shutdownOutput()
            asc.shutdownInput()
            asc.close()
        }
    }

    companion object {
        private val lgr = LoggerFactory.getLogger(SanchuanAioTest::class.java)
    }
}